package com.ccl.iot.huiju.presenter;

import android.os.Handler;
import android.util.SparseArray;
import android.view.View;

import com.ccl.iot.bean.IOTHuiJuBean;
import com.ccl.iot.huiju.IOTHuiJu;
import com.ccl.iot.huiju.contract.MainContract;
import com.ccl.iot.huiju.db.IOTDaoUtil;
import com.ccl.iot.huiju.util.HuiJuUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 类说明：
 * 作者：HD on 2017/11/20 14:55
 * 邮箱：hehandong@qq.com
 */

public class MainPresenterImpl implements MainContract.MainPresenter {

    private MainContract.MainView mView;
    private ArrayList<IOTHuiJu> mIOTHuiJuList;

    private Handler mHandler = new Handler();

    public MainPresenterImpl(MainContract.MainView view){
        mView = view;
    }

    public void setData(ArrayList<IOTHuiJu> iotHuiJuList){
        mIOTHuiJuList = iotHuiJuList;
    }


    @Override
    public void refreshPage(int pageIndex) {
        if (pageIndex < 0) {
            pageIndex = 0;
        }

        //下一页的数据
        final List<IOTHuiJuBean> nextPageList = IOTDaoUtil.queryDataFromPage(pageIndex + 1);

        //当前页的数据
        final SparseArray<IOTHuiJu> dataList = HuiJuUtil.getPageData(pageIndex, mIOTHuiJuList);

        final int finalPageIndex = pageIndex;

        mHandler.post(new Runnable() {
            @Override
            public void run() {

                if (finalPageIndex == 0){
                    mView.setLeftLayoutVisibility(View.INVISIBLE);
                }else {
                    mView.setLeftLayoutVisibility(View.VISIBLE);
                }

                if (nextPageList != null && nextPageList.size() > 0){
                    mView.setRightLayoutVisibility(View.VISIBLE);

                }else {
                    mView.setRightLayoutVisibility(View.INVISIBLE);
                }

                if (dataList != null) {

                    int size = dataList.size();
                    if (size >= 0) {
                        mView.notifyDataSetChanged(dataList, finalPageIndex,size);
                    }
                }
            }
        });


    }

    @Override
    public void switchPage(int pageIndex, boolean isAdd) {

        if (isAdd) {
            List<IOTHuiJuBean> currentPageList = IOTDaoUtil.queryDataFromPage(pageIndex);
            if (currentPageList != null && currentPageList.size() > 0) {
                pageIndex++;
                List<IOTHuiJuBean> nextPageList = IOTDaoUtil.queryDataFromPage(pageIndex);
                if (nextPageList != null && nextPageList.size() > 0) {
                    refreshPage(pageIndex);
                }
            }
        } else {
            pageIndex--;
            refreshPage(pageIndex);
        }
    }
}
